package dbkey

import (
	"login"
	"fmt"
	"net/http"
	"time"
	"appengine/datastore"
	"appengine"
	"appengine/user"
)

type RemoteKey struct {
	Content string
	UpdateTime time.Time
}

func Do (w http.ResponseWriter, r *http.Request) {

	c := appengine.NewContext(r)

	pass, errMsg := login.Check(r)

	if !pass {
		errReturn(w, errMsg)
		return
	}

	action := r.FormValue("action")
	if action == "set" {
		if r.FormValue("key") == "" {
			errReturn(w, "please offer a key to set")
			return
		}
		k := RemoteKey {
			Content:	r.FormValue("key"),
			UpdateTime:	time.Now(),
		}
		_ , err := datastore.Put(c, datastore.NewKey(c, "RemoteKey", user.Current(c).ID, 0, nil), &k)
		if err == nil {
			setSucc(w)
			return
		} else {
			errReturn(w, err.Error())
			return
		}
	} else if action == "get" {
		var entity RemoteKey
		if err := datastore.Get(c, datastore.NewKey(c, "RemoteKey", user.Current(c).ID, 0, nil), &entity); err == nil {
			getSucc(w, entity.Content)
			return
		} else {
			errReturn(w, err.Error())
			return
		}
	} else if action == "search" {
		q := datastore.NewQuery("RemoteKey").search().Filter("Content =", r.FormValue("q"))

		t := q.Run(c)
		var entity RemoteKey
		_, err := t.Next(&entity)
		if err == datastore.Done {
			fmt.Fprint(w, "not found")
		} else if err != nil {
			errReturn(w, err.Error())
			return
		} else {
			fmt.Fprint(w, "found")
		}
	} else if r.FormValue("action") == "" {
		errReturn(w, "must specify an action")
		return
	} else {
		errReturn(w, "unknown action \"" + r.FormValue("action") + "\"")
		return
	}
}

func errReturn(w http.ResponseWriter, errMsg string) {
	fmt.Fprint(w, "err: ", errMsg)
}

func setSucc(w http.ResponseWriter) {
	fmt.Fprint(w, "set key succ!")
}

func getSucc(w http.ResponseWriter, rk string) {
	fmt.Fprint(w, rk)
}
